<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>小数计算</title>
</head>
<body>
<script>
    if (!Number.EPSILON) {
        Number.EPSILON = Math.pow(2, -52)
    }
    var a = 0.1 + 0.2;
    var b = 0.3;

    function numbersCloseEnoughToEqual(n1, n2) {
        return Math.abs(n1 - n2) < Number.EPSILON
    }

    console.log(numbersCloseEnoughToEqual(a, b));

    // 解决小数相加不准确
    function add(num1, num2) {
        // 先把小数扩大成整数，然后相加，完了再除回去
        let n = 0;
        // 先判断小数
        if (num1.toString().split('.').length > 1) {
            n = num1.toString().split('.')[1].length;
        }
        if (num2.toString().split('.').length > 1) {
            n = Math.max(n, num2.toString().split('.')[1].length);
        }
        n = Math.pow(10, n);
        return (num1 * n + num2 * n) / n;
    }

    console.log(add(0.1, 0.2));
</script>
</body>
</html>
